﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DoubleH.Utility.Configuration;
using FCNS.Data;
using Table = FCNS.Data.Table;
using System.Diagnostics;

namespace DataExchange
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            InitVar();
            RefreshDataNow();
            InitEvent();
        }

        bool canClose = false;
        DataConfig dataConfig = null;
        DataExchangeConfig dataExchangeConfig = null;
        System.Timers.Timer timerData = null;//这个玩意是异线程了，要注意。
        Dictionary<string, int> dataIndex = new Dictionary<string, int>();

        private void InitVar()
        {
            dataExchangeConfig = (DataExchangeConfig)ConfigSerializer.LoadConfig(typeof(DataExchangeConfig), DbDefine.baseDir + "DataExchangeConfig.xml", false);

            dataConfig = DoubleHConfig.AppConfig.DataConfigItems.FirstOrDefault(f => { return f.Flag == DoubleHConfig.AppConfig.DataFlag; });
            if (dataConfig == null)
            {
                listBoxLog.Items.Add("数据库配置错误");
                Environment.Exit(0);
            }
            listBoxLog.Items.Add(DateTime.Now + ":数据交换器启动");

            FCNS.Data.SQLdata.SqlConfig = new FCNS.Data.SQLdata.SqlString((FCNS.Data.DataType)Enum.Parse(typeof(FCNS.Data.DataType), dataConfig.DataType), dataConfig.DataAddress,
                dataConfig.DataName, dataConfig.Port, dataConfig.DataUser, dataConfig.DataPassword, dataConfig.TimeOut, dataConfig.HttpPort);


            labelTime.Content = "下次数据交换时间为：" + DateTime.Now.AddMinutes(dataExchangeConfig.DataExchangeTime);
            if (!string.IsNullOrEmpty(dataExchangeConfig.PosOffLineDataIndex))
            {
                foreach (string s1 in dataExchangeConfig.PosOffLineDataIndex.Split(';'))
                {
                    if (string.IsNullOrEmpty(s1))
                        continue;

                    string[] s2 = s1.Split(':');
                    if (s2.Length != 2)
                        continue;

                    int i = -1;
                    System.Diagnostics.Debug.Assert(int.TryParse(s2[1], out i));
                    dataIndex.Add(s2[0], i);
                }
            }
            timerData = new System.Timers.Timer();
            timerData.Interval = dataExchangeConfig.DataExchangeTime * 60000;
            timerData.Enabled = true;
            timerData.Start();

            this.Hide();
            DoubleH.Utility.WindowsUtility.SetStartWithWindows(true, FCNS.Data.DbDefine.baseDir + "DataExchange.exe");
        }

        private void InitEvent()
        {
            timerData.Elapsed += (ss, ee) => StartTimer();

            this.Closing += (ss, ee) => CloseThis(ee);
            显示MenuItem.Click += (ss, ee) => this.Show();
            退出MenuItem.Click += (ss, ee) => CloseNow();
            系统配置MenuItem.Click += (ss, ee) => ShowConfig();
            数据检查MenuItem.Click += (ss, ee) => CheckData();
            请货单MenuItem.Click += (ss, ee) => BuildPosRequest();

            buttonRefresh.Click += (ss, ee) => RefreshDataNow();
        }

        private void BuildPosRequest()
        {
            Table.UserS.LoginUser = DoubleH.Utility.Login.LoginUtility.MiniLogin();
            if (Table.UserS.LoginUser == null)
            {
                DoubleH.Utility.MessageWindow.Show("请登录");
                return;
            }
            DoubleH.Utility.Configuration.DoubleHConfig.UserConfig = DoubleH.Utility.Configuration.ConfigSerializer.LoadUserConfig(Table.UserS.LoginUser.Id);

            Table.PosS pos = Table.PosS.GetObject(DoubleHConfig.AppConfig.PosNO);
            Debug.Assert(pos != null);
            PosUtility.QingHuoDan qhd = new PosUtility.QingHuoDan();
            qhd.Init(pos);
            qhd.ShowDialog();
            Table.UserS.LoginUser = null;//必须要这样，防止pos收款的用户和做请货单的用户不相同。
        }

        private void CheckData()
        {
            LoadLocalDbFile();
            cmdSqlite.CommandText = "select count(*) from PosShiftS where EndDateTime not like '' order by Id desc limit 50 ";
            object obj = cmdSqlite.ExecuteScalar();
            DisposeLocalDbFile();
            if (obj != null)
                MessageBox.Show("交班记录存在 " + obj.ToString() + " 条异常");
        }

        private void RefreshDataNow()
        {
            if (System.IO.File.Exists(DbDefine.dbFile))//防止首次运行没有数据文件导致报错
                StartTimer();

            DownloadServerData();
        }

        private void ShowConfig()
        {
            MainConfig mc = new MainConfig();
            mc.Init(dataExchangeConfig);
            mc.ShowDialog();
        }

        private void StartTimer()
        {
            BackupRemote();
            UploadOfflineData();
            
            labelTime.Dispatcher.Invoke(new Action(() =>
            {
                labelTime.Content = "下次数据交换时间为：" + DateTime.Now.AddMinutes(dataExchangeConfig.DataExchangeTime);
            }));
        }

        private void CloseNow()
        {
            canClose = true;
            this.Close();
        }

        private void CloseThis(System.ComponentModel.CancelEventArgs ee)
        {
            if (canClose)
                return;

            ee.Cancel = true;
            this.Hide();
        }
    }
}